package com.wan37.logic.task.dao.impl;

import com.wan37.logic.task.dao.TaskDao;
import com.wan37.logic.task.domain.entity.TaskDO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : luoyong
 * @date : 2020-08-08 14:48
 **/
@Repository
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public class TaskDaoImpl implements TaskDao {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    @Override
    public List<TaskDO> findTaskDO(TaskDO taskDO) {
        return (List<TaskDO>) hibernateTemplate.find("from TaskDO " +
                "where userId=? and taskParentType=? and taskSonType=?",taskDO.getUserId(),
                taskDO.getTaskParentType(),taskDO.getTaskSonType());
    }

    @Override
    public List<TaskDO> findTaskDOByUserId(String userId) {
        return (List<TaskDO>) hibernateTemplate.find("from TaskDO where userId=?",userId);
    }

    @Override
    public boolean add(TaskDO taskDO) {
        hibernateTemplate.save(taskDO);
        return true;
    }

    @Override
    public boolean delete(Integer id) {
        return false;
    }

    @Override
    public boolean update(TaskDO taskDO) {
        Session session = hibernateTemplate.getSessionFactory().getCurrentSession();
        Query query = session.createQuery("update TaskDO set taskId=?,total=? where userId=? and taskParentType=? and taskSonType=?");
        query.setParameter(0, taskDO.getTaskId());
        query.setParameter(1, taskDO.getTotal());
        query.setParameter(2, taskDO.getUserId());
        query.setParameter(3, taskDO.getTaskParentType());
        query.setParameter(4, taskDO.getTaskSonType());
        query.executeUpdate();
        return true;
    }

    @Override
    public List<TaskDO> getAll() {
        return (List<TaskDO>) hibernateTemplate.find("from TaskDO ");
    }
}
